<template>
  <div class="priceSet">
    <div class="priceSet-head">
      <div class="btns">
        <el-button-group>
          <el-button class="btn-5" 
            :class="{'active': isActive === 'Bill'}" 
            @click="getBillRecords('Bill')"  
            v-jurisdiction="'order:info:customer:list'"
            >订单记录</el-button>
          <el-button 
            class="btn-5"
            :class="{'active': isActive === 'addBill'}" 
            @click="addBill('addBill')" v-jurisdiction="'customer:order:save'">新建账单</el-button>
        </el-button-group>
      </div>
      <div class="right-btns">
        <el-button class="btn-5" v-if ="isActive === 'addBill'" v-jurisdiction="'customer:order:save'"  @click="saveOrderData">保存</el-button>
        <!-- <el-button class="btn-5" v-if ="isActive === 'addBill'" v-jurisdiction="'customer:order:add'" @click="saveOrder">确定</el-button> -->
        <el-button class="btn-5" v-if ="isActive === 'addBill'"  @click="saveToCharge" >确定去收费</el-button>
      </div>
    </div>

    <div class="priceSet-content">
      <!-- 订单记录 -->

      <div class="content-table" v-if="isActive === 'Bill'">
        <ztable 
          :tableData='data'
          :data="tableData" 
          :border='false'
          
          :strucs='columns'
          :columns='strucs'
          
          
          :isShow="true"
          @handleExpandChange="handleExpandChange"
          type='expand'
          :height="'100%'"
          :isshowOperation="true"
        >
            <template #default="slotData">
              <el-button 
                type="text" 
                size="small" 
                class="operation" 
                v-if="slotData.rowData.status === '新建'" 
                @click="handleEditItem(slotData.rowData.id)"
                >编辑</el-button>
              <el-button 
                type="text" size="small" 
                class="operation" 
                @click="handleCompleteAll(slotData.rowData)"
                v-if="slotData.rowData.status !== '结束'" 
                >完成</el-button>
                <el-button 
                type="text" size="small" 
                class="operation" 
                @click="handleDelItem(slotData.rowData)"
                v-jurisdiction="'customer:order:new:del'"
                >删除</el-button>
              
            </template>
            <template #insideBtn="scope">
              <el-button 
                type="text" size="small" 
                class="operation" 
                @click="handleComplete(scope.insideData)"
                v-if="scope.insideData.status !== '结束'" 
                >完成</el-button>
              <!-- <el-button type="text" size="small" class="operation" >打印</el-button> -->
            </template>
        </ztable>
      </div>

      <!-- 新建账单 -->
      <div class="newbill" v-show ="isActive === 'addBill'" >
        <newbill :id="id" ref="newbillRef" :historyData="historyList" :orderId="orderId"></newbill>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs, computed, watch, watchEffect, onMounted, nextTick } from "vue"
import useRequet, { RespData } from '../../../hook/network';
import request from '../../../hook/request';
import useConfgin from '../../../hook/getconfig'
import useRequest from '../../../hook/request';
import ztable from "../../../components/Table/index.vue";
import newbill from "./chargeModel/newbill.vue"
import { ElMessage, ElMessageBox } from 'element-plus';
import { debounce } from '../../../utils/debounce';
import { useRoute } from 'vue-router';

import { delOrderApi } from '../../../api/order';


// 订单记录
const configIDOrder = 553
// 订单嵌套
const configIDDeepOrder = 554
export default defineComponent({
  name: 'PriceSet',
  components: {
    newbill,
    ztable
  },
  setup() {
    const route = useRoute()
    
    let id: any = route.params.id
    watch(() => route.params.id, (newId) => {
      console.log(route)
      id = newId

      if(newId) {
        getList()
      }
    })

    watchEffect(() => {
      
      if(route.query.type) {
        window.localStorage.setItem('activeName', String(route.query.type))
      }
      onMounted(() => {
        console.log('ces')
        if(route.query.add) {
          addBill('addBill')
        }

        if(route.query.toDetailId) {
        // addBill('addBill')
        handleEditItem(Number(route.query.toDetailId))
      }
      })
      
    })
    
    const list = reactive({
      loading: false,
      // 账单数据
      data: [],
      // 嵌套数据
      tableData: [] as any[],
      // 订单记录数据
      columns: <any>[],
      
      // 嵌套结构
      strucs: <any>[]
    })

    const rowListOrder = useConfgin(configIDOrder)
    list.columns = rowListOrder.groupDataList.value;
    const rowListDeepOrder = useConfgin(configIDDeepOrder)
    list.strucs = rowListDeepOrder.groupDataList.value;

    const request = useRequet({ path: "" });
    const getList = async() => {
      let params = {
        customerId: id
      }
      let result:any = await useRequest(`pay/order/getCustomerOrderList`, params, 'POST')
      if(result.code !== 0) return ElMessage.error('订单列表获取' + result.msg)
      list.data = result.data || []
    }
    getList()
    
    // 展开
    const handleExpandChange = async(row: any) => {
      let id = row.id
      
      let result:any = await useRequest(`pay/order/getOrderDetail/${id}`, {}, 'GET')
      let index = list.data.findIndex((i: any) => i.id === id)
      await nextTick()
      list.tableData[index] = result.data || []

    }
    const orderId = ref(0)
    // 编辑
    const handleEditItem = (id: number) => {
      orderId.value = id
      request.sendRequest({
        address: `pay/order/getOrderDetail/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('订单列表获取' + resp.msg)
          let list = resp.data || []
          list.forEach((i: any) => {
            i.toothBit = JSON.parse(i.toothBit)
          })
          historyData.historyList = list || []
          isActive.value = 'addBill'
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
      
    }

    // 删除划价单
    const handleDelItem = (rowData: any) => {
      let id = rowData.id
      ElMessageBox.confirm('此操作将永久删除该订单， 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
				let res:any = await delOrderApi({}, rowData.id)
        if(res.code !== 0) return ElMessage.error('操作' + res.msg)
        ElMessage.success('删除成功');
        getList()
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }

    // 全部完成
    const handleCompleteAll = (rowData: any) => {
      let id = rowData.id
      ElMessageBox.confirm('此操作将设置【所有订单项目】为完成, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
				let result:any = await useRequest(`pay/order/setOrderAllEnd/${id}`, {}, 'POST')
        if(result.code !== 0) return ElMessage.error('操作' + result.msg)
        getList()
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }

    // 完成
    const handleComplete = (rowData: any) => {
      let id = rowData.id
      ElMessageBox.confirm(`此操作将设置【订单项目】为完成', 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
				let result:any = await useRequest(`pay/order/setDetailEnd/${id}`, {}, 'POST')
        if(result.code !== 0) return ElMessage.error('操作' + result.msg)
        getList()
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })

    }
    const newbillRef = ref<any>(null)

    const historyData = reactive({
      historyList: [] as any[]
    })
    
    
    const isActive = ref('Bill')

    const getBillRecords = (val: string) => {
      isActive.value = val
      getList()

    }

    const addBill = (val: string) => {
      console.log('执行了addBill')
      newbillRef.value.getCustomerDebtOrder(id)
      // newbillRef.value.getPayMent()
      newbillRef.value.getLastOrderAdd(id)
      isActive.value = val
    }

    const saveOrder = () => {
      newbillRef.value.saveOrder()
    }

    // 防抖
    const clickSaveOrder = () => {
      console.log('点击了')
      newbillRef.value.saveOrderData()
    }
    const debounceClick = debounce(clickSaveOrder, 1000)
    // 保存订单， 防止网络慢多次调用接口
    const saveOrderData = () => {
      debounceClick()
    }
    

    const saveToCharge = () => {
      newbillRef.value.saveToCharge()
    }

    return {
      id,
      ...toRefs(list),
      
      isActive,
      newbillRef,
      ...toRefs(historyData),
      getBillRecords,

      orderId,
      getList,
      handleExpandChange,
      handleCompleteAll,
      handleComplete,
      handleEditItem,
      handleDelItem,

      addBill,
      saveOrder,
      saveOrderData,
      saveToCharge
    }
  }
})
</script>

<style lang="scss" scoped>
@import '@style/extend';
.priceSet {
  display: flex;
  flex-direction: column;
  min-height: 500px;
  height: calc(100% - 40px);
  .priceSet-head {
    height: 40px;
    line-height: 40px;
    border-bottom: 2px solid $mainColor;
    display: flex;

    .btns {
      padding: 0 20px 0 20px;
    }

    .right-btns {
      text-align: right;
      flex: 1;
      padding-right: 10px;
    }
  }

  .priceSet-content {
    height: 100%;
    display: flex;
    flex-direction: column;
    // overflow: auto;

    .content-top {
      width: 100%;
      height: 120px;
      background: $a2-Color;
      border-radius: $radius-1;
      box-shadow: 1px 1px 3px #ccc;
      display: flex;
      .charge-info {
        display: flex;
        flex-direction: column;
        // width: 100%;
        height: 100%;
        padding: 10px 30px 10px 30px;
        box-sizing: border-box;
        justify-content: center;
        position: relative;
        .info-title {
          @extend .standard-5;
          margin-bottom: 20px;
          
        }
        .info {
          display: flex;
          .info-1 {
            font-size: $fontSize;
            padding-right: 20px;
            & > div:last-child {
              padding-top: 10px;
              font-weight: 600;
            }
          }
        }
      }
      .charge-info::before {
        content: '';
        display: block;
        position: absolute;
        width: 1px;
        height: 80px;
        background: $mainColor;
        top: 20px;
        right: 0;
      }
    }

    .content-table {
      height: 100%;
    }

    .newbill {
      overflow-y: auto;
      // padding: 10px 20px;
    }
  }

}
</style>